﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Collections;
using System.Management;

public partial class LogicLayer
{
	#region User
	/// <summary>
	/// 登录
	/// </summary>
	/// <returns>-1 failed 0 success 1 failed 2 nolic </returns>
	public int Logon(string userName, string userPwd, HttpContext context)
	{
		try
		{
			if (!VerifyLicense())
				return 2;

			int result = 0;

			string enPwd = userPwd;
			if (!string.IsNullOrEmpty(userPwd))
				enPwd = Helper.Encrypt(userPwd);

			Database db = DatabaseFactory.CreateDatabase();
			//Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("connStr");

			string sql = "select count(*) from SYS_User where UserName=@UserName and Password=@UserPwd and Disabled=0";
			DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@UserName", DbType.String, userName);
			db.AddInParameter(cmd, "@UserPwd", DbType.String, enPwd);

			int n = (int)db.ExecuteScalar(cmd);
			if (n > 0)
				context.Session["CurrentUserName"] = userName;
			else
				result = 1;

			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("Logon:" + ex.Message);
			return -1;
		}
	}

	/// <summary>
	/// 注销
	/// </summary>
	public void Logoff(HttpContext context)
	{
		try
		{
			context.Session.Remove("CurrentUserName");
		}
		catch { }
	}

	public int ChangePwd(string userName, string userPwd, string newPwd)
	{
		try
		{
			int result = 0;

			string enPwd = userPwd;
			if (!string.IsNullOrEmpty(userPwd))
				enPwd = Helper.Encrypt(userPwd);

			string enPwdNew = newPwd;
			if (!string.IsNullOrEmpty(newPwd))
				enPwdNew = Helper.Encrypt(newPwd);

			Database db = DatabaseFactory.CreateDatabase();
			//Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("connStr");

			string sql = "select count(*) from SYS_User where UserName=@UserName and Password=@UserPwd and Disabled=0";
			DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@UserName", DbType.String, userName);
			db.AddInParameter(cmd, "@UserPwd", DbType.String, enPwd);

			int n = (int)db.ExecuteScalar(cmd);
			if (n == 0)
				return 1;//旧密码不匹配
			else
			{
				cmd.CommandText = "update SYS_User set Password=@UserPwd where UserName=@UserName";
				cmd.Parameters.Clear();
				db.AddInParameter(cmd, "@UserName", DbType.String, userName);
				db.AddInParameter(cmd, "@UserPwd", DbType.String, enPwdNew);
				db.ExecuteNonQuery(cmd);
			}

			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("ChangePwd:" + ex.Message);
			return -1;
		}
	}
	#endregion

	#region Column
	public List<CMS_Columns> ListColumns(string parentID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select * from CMS_Columns where ParentID=@ParentID and disabled=0 order by SequenceNo";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@ParentID", DbType.String, parentID);

			List<CMS_Columns> result = new List<CMS_Columns>();
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				while (dataReader.Read())
				{
					CMS_Columns obj = GetCMS_ColumnsFromDataReader(dataReader);
					if (obj != null)
						result.Add(obj);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("ListColumns:" + ex.Message);
			return null;
		}
	}

	public bool HasChildColumn(string parentID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select count(*) from CMS_Columns where ParentID=@ParentID and disabled=0";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@ParentID", DbType.String, parentID);

			int r = (int)db.ExecuteScalar(cmd);

			if (r > 0)
				return true;
			else
				return false;
		}
		catch (Exception ex)
		{
			Logger.Write("HasChildColumn:" + ex.Message);
			return false;
		}
	}

	/// <summary>
	/// 得到栏目号(父栏目号+ 自增量二位号)
	/// </summary>
	public string GenerateColumnID(string parentID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select count(*) from CMS_Columns where ParentID=@ParentID";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@ParentID", DbType.String, parentID);

			int r = (int)db.ExecuteScalar(cmd);

			r++;

			string result = parentID + r.ToString().PadLeft(2, '0');

			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("GenerateColumnID:" + ex.Message);
			return "";
		}
	}

	public bool DisableColumns(string columnID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "update CMS_Columns set Disabled=1 where ColumnID=@ColumnID";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@ColumnID", DbType.String, columnID);

			db.ExecuteNonQuery(cmd);
			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("DisableColumns:" + ex.Message);
			return false;
		}
	}

	/// <summary>
	/// 获得顶级栏目
	/// </summary>
	/// <param name="columnID"></param>
	/// <returns></returns>
	public CMS_Columns GetTopColumn(string columnID)
	{
		try
		{
			CMS_Columns result = GetCMS_Columns(columnID);
			if (result != null)
			{
				CMS_Columns parent = GetTopColumn(result.ParentID);
				if (parent != null)
					result = parent;
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("GetTopColumn:" + ex.Message);
			return null;
		}
	}

	public bool UpdateColumnSequenceNo(string columnID, string sequenceNo)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "update CMS_Columns set SequenceNo=@SequenceNo where ColumnID=@ColumnID";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			db.AddInParameter(cmd, "@SequenceNo", DbType.String, sequenceNo);
			db.AddInParameter(cmd, "@ColumnID", DbType.String, columnID);

			db.ExecuteNonQuery(cmd);
			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("UpdateColumnSequenceNo:" + ex.Message);
			return false;
		}
	}
	#endregion

	#region Article
	public List<CMS_Article> ListCMS_Article(string columnID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select * from CMS_Article where disabled=0 and ColumnID=@ColumnID order by SequenceNo,CreateTime";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@ColumnID", DbType.String, columnID);

			List<CMS_Article> result = new List<CMS_Article>();
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				while (dataReader.Read())
				{
					CMS_Article obj = GetCMS_ArticleFromDataReader(dataReader);
					if (obj != null)
						result.Add(obj);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("ListCMS_Article:" + ex.Message);
			return null;
		}
	}

	public bool DisableArticle(string articleID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "update CMS_Article set Disabled=1 where ArticleID=@ArticleID";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			db.AddInParameter(cmd, "@ArticleID", DbType.String, articleID);

			db.ExecuteNonQuery(cmd);
			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("DisableArticle:" + ex.Message);
			return false;
		}
	}

	/// <summary>
	/// 列出同一目录下的所有文章
	/// </summary>
	public List<CMS_Article> ListArticleInOneColumn(string articleID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select * from CMS_Article where ColumnID=(select columnID from CMS_Article where disabled=0 and ArticleID=@ArticleID) and disabled=0  order by SequenceNo ";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@ArticleID", DbType.String, articleID);

			List<CMS_Article> result = new List<CMS_Article>();
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				while (dataReader.Read())
				{
					CMS_Article obj = GetCMS_ArticleFromDataReader(dataReader);
					if (obj != null)
						result.Add(obj);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("ListArticleInOneColumn:" + ex.Message);
			return null;
		}
	}

	/// <summary>
	/// 列出第一个目录（首页）下的所有文章
	/// </summary>
	public List<CMS_Article> ListArticleInFirstColumn()
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select * from CMS_Article where ColumnID=(select top 1 columnID from CMS_Columns where disabled=0 order by SequenceNo) and disabled=0  order by SequenceNo ";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			List<CMS_Article> result = new List<CMS_Article>();
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				while (dataReader.Read())
				{
					CMS_Article obj = GetCMS_ArticleFromDataReader(dataReader);
					if (obj != null)
						result.Add(obj);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("ListArticleInFirstColumn:" + ex.Message);
			return null;
		}
	}

	/// <summary>
	/// 得到第一级导航栏的Url
	/// </summary>
	public string GetTopNavMenuUrl(string columnID)
	{
		try
		{
			string result = "";

			if (HasArticle(columnID))
			{
				Database db = DatabaseFactory.CreateDatabase("connStr");
				string sql = "select top 1 * from CMS_Article where ColumnID=@ColumnID and disabled=0  order by SequenceNo ";
				System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
				db.AddInParameter(cmd, "@ColumnID", DbType.String, columnID);

				CMS_Article art = new CMS_Article();
				using (IDataReader dataReader = db.ExecuteReader(cmd))
				{
					if (dataReader.Read())
					{
						art = GetCMS_ArticleFromDataReader(dataReader);
					}
				}
				if (art != null)
					result = "/templates/subArticle.aspx?cid=" + columnID + "&aid=" + art.ArticleID;
			}
			else
			{
				result = "/templates/subColumn.aspx?pid=" + columnID ;
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("GetTopNavMenuUrl:" + ex.Message);
			return "";
		}
	}

	/// <summary>
	/// 判断栏目下有没有文档
	/// </summary>
	public bool HasArticle(string columnID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select count(*) from CMS_Article where ColumnID=@ColumnID and disabled=0";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@ColumnID", DbType.String, columnID);

			int r = (int)db.ExecuteScalar(cmd);
			if (r > 0)
				return true;
			else
				return false;
		}
		catch (Exception ex)
		{
			Logger.Write("HasArticle:" + ex.Message);
			return false;
		}
	}

	public List<CMS_Article> ListArticles(string columnID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select * from CMS_Article where ColumnID=@ColumnID and disabled=0  order by SequenceNo ";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@ColumnID", DbType.String, columnID);

			List<CMS_Article> result = new List<CMS_Article>();
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				while (dataReader.Read())
				{
					CMS_Article obj = GetCMS_ArticleFromDataReader(dataReader);
					if (obj != null)
						result.Add(obj);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("ListArticles:" + ex.Message);
			return null;
		}
	}

	/// <summary>
	/// 得到栏目下文章的数量
	/// </summary>
	public int GetArticleSum(string columnID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select count(*) from CMS_Article where ColumnID=@ColumnID and disabled=0";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@ColumnID", DbType.String, columnID);

			return (int)db.ExecuteScalar(cmd);
		}
		catch (Exception ex)
		{
			Logger.Write("GetArticleSum:" + ex.Message);
			return 0;
		}
	}

	public string GetBreadcrumbs(string columnID)
	{ 
		if(columnID == "")
			return "";

		string result = "";

		CMS_Columns col = GetCMS_Columns(columnID);
		if (col != null)
		{
			result = col.ColumnName + " > ";
			result = GetBreadcrumbs(col.ParentID) + result;
			//result = result.Substring(0, result.Length - 2);
			return result;
		}
		else
			return "";
	}

	public bool UpdateArticleSequenceNo(string articleID, string sequenceNo)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "update CMS_Article set SequenceNo=@SequenceNo where ArticleID=@ArticleID";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			db.AddInParameter(cmd, "@SequenceNo", DbType.String, sequenceNo);
			db.AddInParameter(cmd, "@ArticleID", DbType.String, articleID);

			db.ExecuteNonQuery(cmd);
			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("UpdateArticleSequenceNo:" + ex.Message);
			return false;
		}
	}
	#endregion

	#region Else
	/// <summary>
	/// 得到banner图片路径
	/// </summary>
	public string GetBannerImgPath(string columnID, string articleID)
	{
		try
		{
			string result = string.Empty;
			if (string.IsNullOrEmpty(columnID) && !string.IsNullOrEmpty(articleID))
			{
				CMS_Article art = GetCMS_Article(articleID);
				if (art != null)
					columnID = art.ColumnID;
			}
			if (string.IsNullOrEmpty(columnID))
				return "";

			CMS_Columns topCol = GetTopColumn(columnID);
			if (topCol != null)
			{
				switch (topCol.ColumnName)
				{
					case "公司业务":
						result = "/img/bn_business.jpg";
						break;
					case "成功案例":
						result = "/img/bn_case.jpg";
						break;
					case "招贤纳士":
						result = "/img/bn_job.jpg";
						break;
					case "合作伙伴":
						result = "/img/bn_partner.jpg";
						break;
					case "关于我们":
						result = "/img/bn_aboutus.jpg";
						break;
					default:
						result = "/img/bn_home.jpg";
						break;
				}
			}

			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("GetBannerImgPath:" + ex.Message);
			return null;
		}
	}


	public bool SortItem(Hashtable hash, string type)
	{
		try
		{
			bool result = true;
			System.Collections.IDictionaryEnumerator enumerator = hash.GetEnumerator();
			while (enumerator.MoveNext())
			{
				if (type == "column")
					result &= UpdateColumnSequenceNo(enumerator.Key.ToString(), enumerator.Value.ToString());
				else
					result &= UpdateArticleSequenceNo(enumerator.Key.ToString(), enumerator.Value.ToString());
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("SortItem:" + ex.Message);
			return false;
		}
	}
	#endregion

	#region License

	public string GetLicenseData()
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select * From SYS_License ";

			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			string result = "";
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				if (dataReader.Read())
				{
					result = dataReader.GetString(0);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("GetLicenseData:" + ex.Message);
			return "";
		}
	}

	public string GetCam()
	{
		try
		{
			string result = string.Empty;

			ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
			ManagementObjectCollection queryCollection = query.Get();

			string mac = string.Empty;
			foreach (ManagementObject mo in queryCollection)
			{
				if (mo["IPEnabled"].ToString() == "True" && mo["ServiceName"].ToString() != "VMnetAdapter")
					mac = mo["MacAddress"].ToString();
				else
					mac = "";

				if (!string.IsNullOrEmpty(mac))
				{
					result = string.Empty;
					string[] array = mac.Split(':');
					for (int i = array.Length - 1; i >= 0; i--)
					{
						result += array[i];
					}
					if (!string.IsNullOrEmpty(result))
						break;
				}
			}
			if (!string.IsNullOrEmpty(result))
				result = "QF-" + result;

			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("GetCam:" + ex.Message);
			return "";
		}
	}

	public bool VerifyLicense()
	{
		string lic = GetLicenseData();

		string cam = GetCam();

		if(string.IsNullOrEmpty(lic) || string.IsNullOrEmpty(cam))
			return false;

		if (string.Compare(Helper.Encrypt(cam), lic) == 0)
			return true;
		else
			return false;
	}

	public bool SubmitLicense(string licKey)
	{
		string lic = licKey;

		string cam = GetCam();

		if (string.IsNullOrEmpty(lic) || string.IsNullOrEmpty(cam))
			return false;

		if (string.Compare(Helper.Encrypt(cam), lic) == 0)
		{
			return UpdateLicense(licKey);
		}
		else
			return false;
	}

	public bool UpdateLicense(string licKey)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "delete From SYS_License ";

			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.ExecuteNonQuery(cmd);

			cmd.CommandText = "insert into SYS_License (LicData) values (@LicData)";
			db.AddInParameter(cmd, "@LicData", DbType.String, licKey);
			db.ExecuteNonQuery(cmd);

			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("UpdateLicense:" + ex.Message);
			return false;
		}
	}
	#endregion

}
